<template>
    <div class="app-container empty-label">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query"
          :filter-list="filterInfo.list"
          :filter-btn="filterInfo.btn"
        >
          <template v-slot:filter-operateTime>
            <el-date-picker
              v-model="operateTime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              range-separator="至"
              :clearable="true"
              :picker-options="$fn.pickerOptionsFn()"
              align="right"
              start-placeholder="操作时间开始日期"
              end-placeholder="操作时间结束日期"
              :shortcuts="$fn.pickerOptionsFn()"
              :default-time="[
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 1, 1, 23, 59, 59),
              ]"
              @change="timeChange"
            ></el-date-picker>
          </template>
        </NewPageFilter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList"></NewPageFilter>
        <select id="selected_device" style="height: 0;width:0;opacity: 0"></select>
      </div>
      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        :pageTotal="pageInfos.pageTotal"
        :api="api"
        v-model:data="tableInfo.data"
        v-model:query="filterInfo.query"
        :tab-index="false"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :pager="true"
        :checkBox="false"
      />
      <page-dialog
        v-show="dialogInfo.visible"
        :title="dialogInfo.title"
        v-model:visible="dialogInfo.visible"
        :width="dialogInfo.width"
        :bt-loading="dialogInfo.btLoading"
        :bt-list="dialogInfo.btList"
        @reset="handleClose"
      >
        <page-form
          ref="tableForm"
          class="paddingBox order-model-formBox flex_wrap_start_start"
          v-model:ref-obj="dialogInfo.formInfo.ref"
          :data="dialogInfo.formInfo.data"
          :field-list="dialogInfo.formInfo.fieldList"
          :rules="dialogInfo.formInfo.rules"
          :label-width="dialogInfo.formInfo.labelWidth"
        >
        <template v-slot:form-printNum="scope">
          <el-form-item 
              :rules="[
                {
                  required: scope.$index >= 0,
                  message: '请输入打印个数',
                  trigger: 'blur',
                },
              ]"
            :prop="dialogInfo.formInfo.data.printNum"
          >
            <el-input-number
              v-model="dialogInfo.formInfo.data.printNum"
              controls-position="right"
              style="width: 175px"
              :clearable="true"
              :precision="0"
              :min="1"
              :max="999999999"
              @change='printNumChange'
              
              placeholder="请输入打印个数"
            />
          </el-form-item>
        </template>
        <!-- printNum -->
        </page-form>
      </page-dialog>
    </div>
  </template>
  
  <script setup name="emptyLabel">
  import {
    getSmartCabinetBlankLabel,
    getStartNo,
    saveAndPrintZpl,
    rfidBindUpdate
  } from "@/api/smartCabinet";
  const { proxy } = getCurrentInstance();
  const selected_device = ref('')
  const idVal = ref('')
  const operateTime = ref(['', '']);
  const isNotUsbDevices = ref('')
  const pageInfos = ref({
    pageSize: 20,
    curPage: 1,
    pageTotal: 0,
  });
  const api = ref("");
  const formRefs = ref('')
  // 过滤相关配置
  const filterInfo = ref({
    query: {
      printStatus: '',
      printUser:'',
      operateTime: "",
    },
    copyQuery: {},
    list: [
      {
        label: "是否打印成功",
        value: "printStatus",
        componentType: "select-model",
        code: "yes_or_no",
        event: search,
      },
      {
        label: '打印人',
        value: 'printUser',
        componentType: 'input',
        event: search,
      },
      {
        slot: true,
        label: "起止日期",
        value: "operateTime",
      },
    ],
    btn: [
      { type: "button", label: "搜索", event: search },
      { type: "button", label: "重置", event: clearSearch },
    ],
    btnList: [
      {
        type: "button",
        label: "打印空白RFID码",
        event: print,
        show: proxy.$permission("emptyLabel:print"),
        disabled: !proxy.$store.state.permission.systemConfig.force_print_in_rfid
      },
    ],
  });
  // 表格相关
  const tableInfo = ref({
    refresh: 1,
    initCurpage: 1,
    data: [],
    fieldList: [
      { label: "起始编号", value: "startNo" },
      { label: "打印个数", value: "printNum" },
      { label: "终止编号", value: "endNo" },
      { label: "备注", value: "remark" },
      { label: "是否打印成功", value: "printStatusValue" },
      { label: "打印人", value: "printUserName" },
      { label: "打印时间", value: "printTime" }
    ],
  });

  const dialogInfo = ref({
    visible: false,
    title: '打印空白RFID码',
    btLoading: false,
    type: '',
    msg: '',
    width: '420px',
    flag: 'page',
    btList: [
      { label: '取消', event: handleClose, show: true },
      {
        label: '打印',
        type: 'primary',
        event: checkConfirm,
        show: true,
      },
    ],
    formInfo: {
      ref: null,
      data: {},
      fieldList: [
        {
          label: '起始编码',
          value: 'startNo',
          type: 'input',
          disabled: true
        },
        {
          label: '打印个数',
          value: 'printNum',
          type: 'slot',
          required: true,
        },
        {
          label: '终止编码',
          value: 'endNo',
          type: 'input',
          disabled: true
        },
        {
          label: '备注',
          value: 'remark',
          type: 'textarea',
        }
      ],
      rules: {
        printNum: [
          {
            required: true,
            message: '请输入打印个数',
            trigger: 'blur',
          },
        ],
      },
      labelWidth: '110px',
    },
  })
  
  onMounted(() => {
     // 
  var devices = [];
  BrowserPrint.getDefaultDevice("printer", function(device){
		//Add device to list of devices and to html select element
		selected_device.value = device;
		devices.push(device);
		var html_select = document.getElementById("selected_device");
		var option = document.createElement("option");
		option.text = device.name;
		html_select.add(option);
		//Discover any other devices available to the application
		BrowserPrint.getLocalDevices(function(device_list){
      if(device_list && device_list.length == 1 && !device_list[0].name) {
        isNotUsbDevices.value = true
      } else {
        isNotUsbDevices.value = false
      }
			for(var i = 0; i < device_list.length; i++)
			{
				//Add device to list of devices and to html select element
				var device = device_list[i];
				if(!selected_device.value || device.uid != selected_device.value.uid)
				{
					devices.push(device);
					var option = document.createElement("option");
					option.text = device.name;
					option.value = device.uid;
					html_select.add(option);
				}
			}
		}, function(){console("Error getting local devices")},"printer");
	}, function(error){
		console.log(error)
	})
  // 
    formRefs.value = [proxy.$refs['tableForm'], dialogInfo.value.formInfo.ref]
    filterInfo.value.copyQuery = proxy.$fn.deepClone(filterInfo.value.query);
    api.value = getSmartCabinetBlankLabel
    getList()
  });

  function printNumChange() {
    dialogInfo.value.formInfo.data.endNo = String(Number(dialogInfo.value.formInfo.data.startNo) + Number(dialogInfo.value.formInfo.data.printNum) - 1)
  }
  function handleClose() {
    dialogInfo.value.visible = false
    dialogInfo.value.formInfo.data.endNo = ''
    dialogInfo.value.formInfo.data.printNum = ''
  }

  function checkConfirm() {
    if(!dialogInfo.value.formInfo.data.printNum){
      proxy.$message({
        message: '请输入打印个数',
        type: 'warning',
      })
      return
    }
    if(isNotUsbDevices.value) {
      proxy.$message({
        message: '打印机未正常连接',
        type: 'warning'
      })
      return
    }
      saveAndPrintZpl(dialogInfo.value.formInfo.data).then((resp) => {
        if (resp && resp.success) {
          
          // 开始打印
          let data = resp.data.zpl
          idVal.value = resp.data.id
          selected_device.value.send(data, finishedCallback, errorCallback)
        }
      })
    
  }
  function finishedCallback() {
    rfidBindUpdate({id: idVal.value, printStatus: 1}).then(res=>{
      dialogInfo.value.visible = false
      getList()
    })
  }

  function errorCallback(errorMessage) {
    console.log(errorMessage)
    rfidBindUpdate({id: idVal.value, printStatus: 0}).then(res=>{
      dialogInfo.value.visible = false
      getList()
    })
  }
    //打印
  function print() {
    getStartNo().then(res=>{
      dialogInfo.value.formInfo.data.startNo = res.data
      dialogInfo.value.visible = true
    })
  }
  
  // 获取列表
  function getList() {
    tableInfo.value.refresh = Math.random();
  }
  function clearSearch() {
    filterInfo.value.query.printStatus = ''
    filterInfo.value.query.printUser = ''
    filterInfo.value.query.operateTime = ''
    operateTime.value = ['', '']
    filterInfo.value.query.startTime = "";
    filterInfo.value.query.endTime = "";
    getList()
  }

  // 搜索
  function search() {
    getList();
  }
  function timeChange(val) {
    if (val && val.length) {
      filterInfo.value.query.startTime = val[0];
      filterInfo.value.query.endTime = val[1];
    } else {
      filterInfo.value.query.startTime = "";
      filterInfo.value.query.endTime = "";
    }
    search();
  }
  </script>
  
  <style lang="scss">
</style>
  